package com.mxf.code.config;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Title:
 * @author mxf 
 * @description 主要就是发送的时候增加消息id，并且保存消息id和消息的对应关系，
 * 因为RabbitTemplate.ConfirmCallback只能拿到消息id，并不能拿到消息内容，
 * 所以需要我们自己保存这种映射关系。在一些可靠性要求比较高的系统中，
 * 你可以将这种映射关系存到数据库中，成功发送删除映射关系，失败则一直发送
 * @createTime  2022/9/14 11:39
 * @param null
 * @paramType 
 * @return 
*/
@Component
public class MessageSender {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public final Map<String, String> unAckMsgQueue = new ConcurrentHashMap<>();

    public void convertAndSend(String exchange, String routingKey, String message) {
        String msgId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(msgId);
        rabbitTemplate.convertAndSend(exchange, routingKey, message, correlationData);
        unAckMsgQueue.put(msgId, message);
    }
    public void convertAndSend(String exchange, String routingKey, final String message,
                   final MessagePostProcessor messagePostProcessor) throws AmqpException {
        String msgId = UUID.randomUUID().toString();
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(msgId);
        rabbitTemplate.convertAndSend(exchange, routingKey, message, messagePostProcessor, correlationData);
        unAckMsgQueue.put(msgId, message);
    }

    public String dequeueUnAckMsg(String msgId) {
        return unAckMsgQueue.remove(msgId);
    }

}